import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

class NotificationService extends GetxService {

  static NotificationService get instance => Get.find();

  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  /// 创建流以便应用程序可以响应与通知相关的事件，因为插件是在 main 函数中初始化的。
  final StreamController<String?> _selectNotificationStream = StreamController<String?>.broadcast();


  Future<NotificationService> init() async {
    _flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()?.requestPermission();
    await _flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');

    /// 这里没有请求权限
    final DarwinInitializationSettings initializationSettingsDarwin =
    DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
      onDidReceiveLocalNotification:
          (int id, String? title, String? body, String? payload) async {},
    );
    final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsDarwin,
    );
    await _flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse:
            (NotificationResponse notificationResponse) {
          switch (notificationResponse.notificationResponseType) {
            case NotificationResponseType.selectedNotification:
              _selectNotificationStream.add(notificationResponse.payload);
              break;
            case NotificationResponseType.selectedNotificationAction:
              break;
          }
        });
    return this;
  }

  Future<void> requestPermissions() async {
    if (Platform.isIOS || Platform.isMacOS) {
      await _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
      await _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          MacOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
        alert: true,
        badge: true,
        sound: true,
      );
    } else if (Platform.isAndroid) {
      final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
      _flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();

      await androidImplementation?.requestPermission();
    }
  }

  void configureSelectNotificationSubject(BuildContext context) {
    _selectNotificationStream.stream.listen((String? payload) {
      if (payload != null && payload.isNotEmpty) {
        Navigator.of(context).pushNamed(payload);
      }
    });
  }

  Future<void> showNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your channel id', 'your channel name',
        channelDescription: '你的频道描述',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');
    // iOS 通知配置
    const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails(
      presentAlert: false, // 显示通知
      presentBadge: false,  // 在应用图标上显示通知标记
      presentSound: false,  // 播放通知声音
    );
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
      iOS: iosNotificationDetails,
    );
    await _flutterLocalNotificationsPlugin.show(
        0, '系统通知', '到时间啦，你今天记账了吗？', notificationDetails);
  }

  Future<void> scheduleNotification(DateTime dateTime) async {
    await initializeTimezone();
    tz.TZDateTime zonedTime = tz.TZDateTime.local(dateTime.year, dateTime.month,dateTime.day-1, dateTime.hour,dateTime.minute);

    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('App', 'AccountBook',
        channelDescription: '通知',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');
    // iOS 通知配置
    const DarwinNotificationDetails iosNotificationDetails = DarwinNotificationDetails(
      presentAlert: false, // 显示通知
      presentBadge: false,  // 在应用图标上显示通知标记
      presentSound: false,  // 播放通知声音
    );
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
      iOS: iosNotificationDetails,
    );
    await _flutterLocalNotificationsPlugin.zonedSchedule(
        1,
        '温馨提示',
        '你今天记账了吗？',
        zonedTime,
        notificationDetails,
        uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        matchDateTimeComponents: DateTimeComponents.time
    );
  }

  Future<void> cancelAllNotification() async {
    await _flutterLocalNotificationsPlugin.cancelAll();
  }

  Future initializeTimezone() async {
    tz.initializeTimeZones();
  }
}